package com.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.annotation.RateLimit;
import com.boot.constants.StatusConstants;
import com.boot.entity.ImageInfo;
import com.boot.service.IImageInfoService;
import com.boot.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/image")
@Slf4j
public class ImageManageController {
    @Resource
    private IImageInfoService imageInfoService;

    /**
     * 分页查询图片列表
     */
    @RateLimit(limit = 20, windowSec = 60)
    @GetMapping("/list")
    public R<IPage<ImageInfo>> listImages(@RequestParam(defaultValue = "1") Integer pageNum) {
        Page<ImageInfo> page = new Page<>(pageNum, 10);
        QueryWrapper<ImageInfo> wrapper = new QueryWrapper<>();

        wrapper.orderByDesc("created_at");
        IPage<ImageInfo> result = imageInfoService.page(page, wrapper);
        return R.page(result);
    }

    /**
     * 禁用图片（人工下架）
     */
    @RateLimit(limit = 10, windowSec = 60)
    @PostMapping("/{id}/disable")
    public R<Void> disableImage(@PathVariable Long id) {
        ImageInfo imageInfo = imageInfoService.getById(id);
        if (imageInfo == null) {
            return R.error("图片不存在");
        }

        if (StatusConstants.ImageStatus.DISABLED.equals(imageInfo.getStatus())) {
            return R.error("该图片已被禁用");
        }

        imageInfo.setStatus(StatusConstants.ImageStatus.DISABLED);
        imageInfo.setCreatedAt(LocalDateTime.now());

        boolean updated = imageInfoService.updateById(imageInfo);
        return updated ? R.success(null) : R.error("操作失败");
    }
}
